<template>
    <div class='container'>
        <div id="perChoose">
            <div class="searcher" style="padding-top:.4rem;">
                <div class="searcherContainer">
                    <i class="icon njfont nj-sousuo" style="font-size: .75rem;margin: 0 .3rem;"></i>
                    <input style="font-size:.75rem;width:87%;border:none;-webkit-tap-highlight-color:transparent;" type="search" placeholder="请搜索地址" id="search-input" ref='searcher' v-model="keyword">
                </div>
            </div>
            <div id="allmap" style="display:none;">
            </div>
            <div :class="inArea ? 'greenLocation' : 'redLocation'" @click='focusSearcher'>
                <i class="icon njfont nj-dizhi" id='arrow' :style="'color:' + inArea ? '#7FB65F' : 'rgba(243, 65, 11, 0.932)'"></i>
                <p v-if='(choosedBefore || (locationInfo && locationInfo.address))' :style="'color:' + inArea ? '#7FB65F' : 'rgba(243, 65, 11, 0.932)'" class="deliveryAddress">
                    <span style='color:#69685C;fontWeigit:bold'>送至：</span>
                    {{choosedAddress.address || locationInfo.address}}
                </p>
                <p v-else class="deliveryAddressPos" :style="'color:' + inArea ? '#7FB65F' : 'rgba(243, 65, 11, 0.932)'">
                    {{ScopeOutInfo ? ScopeOutInfo.tip : locateStatus}}
                </p>
                <i class="icon njfont nj-youjiantou" id='arrow' :style="'color:' + inArea ? '#7FB65F' : 'rgba(243, 65, 11, 0.932)'"></i>
            </div>
            <!-- 收获地址列表 -->
            <AddressList v-if='showList' @previousAddress='previousAddress' :choosePos='choosePos' :getVaildStoreIdList='getVaildStoreIdList()' ></AddressList>
            <div class="assumeList" ref="assumeList">
                <ul ref="assumeListUL" style="font-size:.8rem;">
                    <li v-for="(item, index) of positionList" :key="index" @click="addPosition(item)" style="-webkit-tap-highlight-color:transparent;">
                        <p v-if="item.inArea" style="color:black;opacity: .9;padding-top:.35rem;">{{item.name}}</p>
                        <p v-if="item.inArea" style="color:black;opacity: .9;">{{item.district}}</p>
                        <p v-if="!item.inArea" style="color:black;opacity: .4;padding-top:.35rem;">{{item.name}}</p>
                        <p v-if="!item.inArea" style="color:black;opacity: .4;">{{item.district}}</p>
                    </li>
                </ul>
            </div>
            <!--  -->
            <div class="deliveryAdd">
                附近地址
            </div>
            <div class="vicinty">
                <ul>
                    <li class="locateSpot">
                        <span @click="firstLocation(locateSpot[0])" class="firstLocation">{{locateSpot[0].address || locateSpot[0].formateAdd || '定位中...'}}</span>   
                        <span @click="relocate" class="relocate" style="color: #80B760;-webkit-tap-highlight-color:transparent;font-size:.8rem;"><i class="icon njfont nj-dingwei1"></i>重新定位</span>
                    </li>
                    <li v-for="(item, index) of vicintyList" :key="index" @click="addLocation(item)" style="-webkit-tap-highlight-color:transparent;" class="nearlySpot">
                        <p v-if="item.inArea" style="color:black;opacity:.7;" :class="index == 0 ? 'firstItem' : 'others'">{{item.name}}</p>
                        <p v-if="!item.inArea" style="color:black;opacity:.3;" :class="index == 0 ? 'firstItem' : 'others'">{{item.name}}</p>
                    </li>
                    <li @click="ToMap" class="moreLocation" style="-webkit-tap-highlight-color:transparent;"><span>更多地址</span><img src="static/image/index-arrow.png" style="width: .5rem;transform: rotate(90deg);"></li>
                </ul>
            </div>
        </div>
        <div class='shade' v-show='positionList.length' @click='clearPositionList'></div>
        <div class='bottomBtn' @click="goAddAddress">
            +新增收货地址
        </div>
    </div>
</template>
<script>
import axios from 'axios';
import { mapGetters, mapActions } from 'vuex';
import { Toast } from "../../utils/toast";
import { showLoading ,hideLoading } from "../../utils/loading";
import AddressList from "./AddressList";
import getSearch from '../../utils/getUrlSearch';
import {getHrefParams} from '../../utils/zx';
import { CHANGE_NAVIGATION, NAVIGATE, CHOOSE_ADDRESS, CHOOSE_ADDRESS_ADD, RECEIVE_DISTANCE } from '../../config/postMessage-types';
export default {
    data () {
        return {
            location:"xxx酒店",
            storeList: [],
            clientHeight: 0,
            positionList: [],   //联想列表
            locateSpot:[{address: '定位中...'}],      //定位点
            vicintyList: [],    //附近点列表
            polygonList:[],     //存储可配送区域
            searchCity:'',
            keyword:'',

            choosedBefore: false,
            choosedAddress: {},
            choosePos: '',
            locateStatus: '定位中...',
            areaList: [],
            inArea: false,
            formerAddressInvaild: false,
            showList: false
        }
    },
    components:{
        AddressList
    },
    computed:{
        ...mapGetters('qxz',{
            locationInfo: 'getLocation',
            ScopeOutInfo: 'getScopeOut'
        }),
        ...mapGetters('qxz', [
            'getAddressList',
            'getChoosedAddress'
        ]),
        ...mapGetters('wxh', [
            'userInfo'
        ]),
        isLogin() {
            return Object.keys(this.userInfo).length;
        },
        fromShopList() {
            return getHrefParams().fromShopList
        },
        addressid() {
            return getHrefParams().addressid
        },
        storeCode() {
            return getHrefParams().storeCode
        }
    }, 
    created() {
        let titleConfig = JSON.stringify({
            type: CHANGE_NAVIGATION,
            params: {
                title: "选择收货地址"
            }
        });
        let test = JSON.stringify({
            type: CHANGE_NAVIGATION,
            params: {
                title: "立即发送"
            }
        });
        window.postMessage(titleConfig);
    },
    async mounted(){
        await this.getStoreList();
        this.showList = true;
        if(this.addressid === 'noAddress') {
            localStorage.removeItem("locateOut");
            localStorage.removeItem("locateIn");
        }else if(this.addressid == -1){
            this.$store.dispatch('qxz/updateLocation', JSON.parse(localStorage.getItem('locateIn')));
            this.$store.dispatch('qxz/updateScopeOut', JSON.parse(localStorage.getItem('locateOut')));
        }
        let _currentPos = JSON.parse(localStorage.getItem("currentPos"));
        // 发送给rn经纬度
        if(_currentPos) {
            let obj = {position:{
                lng: _currentPos.positionlng,
                lat: _currentPos.positionlat
            }}
            var RnParams = {
                type: RECEIVE_DISTANCE,
                params: {
                    currentPos: obj
                }
            }
            window.postMessage(JSON.stringify(RnParams));
        }
        let searcher = this.$refs.searcher;
        this.$route.query.clue && searcher.focus();
        this.judgeInArea()
        this.noExtra();
        this.initScript();
    },
    methods:{
        ...mapActions('qxz', [
            'updateChoosedAddress'
        ]),
        // 开启中的storeId数组
        getVaildStoreIdList() {
            let tempArr = [];
            this.storeList.map(ele => {
                tempArr.push(JSON.stringify(ele.storeId))
            })
            return tempArr;
        },
        async judgeInArea() {
            let address = this.choosedBefore || this.locationInfo || this.ScopeOutInfo;
            this.choosedBefore && (address = this.choosedAddress)
            let inArea = false;
            let defaultInfo = (this.choosedBefore || this.locationInfo) ? true : false
            if(address) {
                let config = {
                    url: api.tmsUrl + 'centralManagerApi/centralManagerObject',
                    method: 'post',
                    data: {
                        judgeInBaselatticeByStoreId: {
                            longitudeandlatitude: address.positionlng + ',' + address.positionlat,
                            storeIdList: that.getVaildStoreIdList()
                        }
                    }
                }
                let res = await axios(config);
                if(res.data.returnCode) {
                    this.inArea = true
                }else {
                    this.inArea = false
                }
            }else {
                this.inArea = false
            }
            
        },
        // 关掉联想列表
        clearPositionList() {
            console.log(this.keyword)
            this.positionList = []
        },
        focusSearcher() {
            this.$refs.searcher.focus();
        },
        // 之前的地址，传过来的
        previousAddress(ele) {
            if(ele === 'scopeOut') {
                this.formerAddressInvaild = true
                return
            }
            if(ele){
                this.choosedBefore = true;
                this.choosedAddress = ele;
            }
            if(this.fromShopList === 'fromShopList') {
                let changeBackBtn = {
                    type: CHANGE_NAVIGATION,
                    params: {
                        eventType: 'goHome',
                        eventParams: {
                            storeCode: ele.storeCode
                        }
                    }
                }
                window.postMessage(JSON.stringify(changeBackBtn));
            }
        },
        //匹配storeCode
        matchStoreCode (storeId) {
            let tempStoreCode;
            console.log(this.storeList,'storesLIst')
            this.storeList.forEach(ele => {
                Number(ele.storeId) === Number(storeId) && (tempStoreCode = ele.storeCode)
            })
            return tempStoreCode;
        },
        //匹配storeId
        matchStoreId (storeCode) {
            let storeId;
            this.storeList.forEach(ele => {
                Number(ele.storeCode) === Number(storeCode) && (storeId = ele.storeId)
            })
            return storeId;
        },
        //发送地址给Rn
        sendAddToRn(obj) {
            let RnParams = {
                type: CHOOSE_ADDRESS,
                params: {
                    ...obj
                }
            }
            window.postMessage(JSON.stringify(RnParams));
        },
        //前往添加地址页面
        goAddAddress(){
            if(this.isLogin) {
                let goBackIns = {
                    type: NAVIGATE,
                    params: {
                        screen: 'AddressControl',
                        params:{
                            createMode: true
                        }
                    }
                }
                window.postMessage(JSON.stringify(goBackIns));
            }else {
                let goBackIns = {
                    type: NAVIGATE,
                    params: {
                        screen: 'Login',
                        params:{
                            FromWeb: true
                        }
                    }
                }
                window.postMessage(JSON.stringify(goBackIns));
            }
        },
        //获取本地储存的当前位置
        getPos(){
            let Pos = JSON.parse(localStorage.getItem("currentPos"));
            return Pos;
        },
        //回到首页
        toHome(){
            this.$router.push('home');
        },
        noExtra(){
            if(localStorage.getItem('currentPos')){
                this.locateSpot = [];
                this.locateSpot.push(JSON.parse(localStorage.getItem('currentPos')));
            }
        },
        //获取门店列表
        async getStoreList(){
            var url = api.base_host + "/baseStore/getRestStore";
            let that = this;
            var params = {
                enterpriseCode: api.enterpriseCode
            }
            var config = {
                url: url,
                methods: "GET",
                params
            }
            let res = await axios(config);
            if(res.data.returnCode === 1){
                let arr = [];
                res.data.data[0].map(ele => {
                    if(ele.businessGoodsIsOpen && !ele.status) {
                        arr.push(ele)
                    }
                })
                that.storeList = arr;
                that.$store.dispatch('qxz/updateStoreList', res.data.data[0]);
            }
        },
        //添加联想列表地址
        addPosition(item){
            if(item.inArea){
                let that = this;
                let obj = new Object();
                AMap.service('AMap.Geocoder',function(){//回调函数
                    //实例化Geocoder
                    let geocoder = new AMap.Geocoder({
                        // city: "010"//城市，默认：“全国”
                    });
                    //TODO: 使用geocoder 对象完成相关功能
                    var lnglatXY=[item.location.lng, item.location.lat];//地图上所标点的坐标
                    geocoder.getAddress(lnglatXY, function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            //获得了有效的地址信息:
                            //即，result.regeocode.formattedAddress
                            obj.province = result.regeocode.addressComponent.province;
                            obj.city = result.regeocode.addressComponent.city || '市辖区';
                            obj.region = result.regeocode.addressComponent.district;
                            // obj.address = result.regeocode.addressComponent.street + result.regeocode.addressComponent.streetNumber + result.regeocode.addressComponent.township;
                            obj.address = result.regeocode.formattedAddress.split(result.regeocode.addressComponent.district)[1];
                            obj.positionlng = item.location.lng;
                            obj.positionlat = item.location.lat;
                            obj.addressid = "-1";
                            // 加入storeCode
                            obj.storeCode = item.storeCode
                            that.$store.dispatch('qxz/updateLocation', obj);
                            localStorage.setItem("locateIn", JSON.stringify(obj));
                            localStorage.setItem("chooseAddressActiveIndex", null);
                            // 发给rn，更新信息
                            that.sendAddToRn(obj);
                            that.previousAddress(obj);
                            that.choosePos = obj;
                            //临时的，防止从地图返回时丢失已选择的地址返回时
                            that.updateChoosedAddress(obj)
                            // 让页面恢复可以滑动
                            let perChoose = document.querySelector('#perChoose');
                            perChoose.style.overflow = 'auto'
                        }else{
                        //获取地址失败
                        }
                    });
                })
                this.positionList = [];
                document.querySelector("#search-input").value = "";
            }else{
                Toast({
                    "message": "该地址不在配送范围内",
			        "duration": 1500,
					"type" : "fail"
                })
            }
        },
        //添加附近地址
        addLocation(item){
            var that = this;
            if(item.inArea){
                var obj = {
					province: item.pname,
					city: item.cityname,
					region: item.adname,
					address: item.address,
					positionlng: item.location.lng,
                    positionlat: item.location.lat,
                    addressid: "-1",
                    storeCode: item.storeCode
                }
                // 发给rn，更新信息
                that.sendAddToRn(obj);
                that.previousAddress(obj);
                that.choosePos = obj;
                //临时的，防止从地图返回时丢失已选择的地址返回时
                that.updateChoosedAddress(obj)
                that.$store.dispatch('qxz/updateLocation', obj);
            }else{
                Toast({
                    "message": "该地址不在配送范围内",
			        "duration": 1500,
					"type" : "fail"
                })
            }
        },
        //附近地址第一个
        firstLocation(item){
            if(item.inArea){
                var obj = {
					province: item.addressComponent.province,
					city: item.addressComponent.city,
					region: item.addressComponent.district,
					address: item.formattedAddress,
					positionlng: item.position.lng,
                    positionlat: item.position.lat,
                    addressid: "-1"
                }
                this.$store.dispatch('qxz/updateLocation', obj);
            }else{
                Toast({
                    "message": "该地址不在配送范围内",
			        "duration": 1500,
					"type" : "fail"
                })
            }
        },
        //初始化高德地图脚本
        initScript() {
            //判断如果有script就删掉
            let that = this;
			if (document.querySelector("#amap-box")){
				document.body.removeChild(document.querySelector("#amap-box"));
			}
			let amapBox = document.createElement("div");
			amapBox.setAttribute("id", "amap-box");
			// this.initMap();
            let script1 = document.createElement("script");
            if(this.getIosVersion()){
				script1.src = 'https://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba';
			}else {
				script1.src = 'https://webapi.amap.com/maps?v=1.4.6&key=9bfe3d8b8882b7d3e4c23e43d38b18ba';
			}
			script1.onload = () => {
                let script2 = document.createElement("script");
                script2.src = "https://webapi.amap.com/ui/1.0/main.js";
				script2.onload = () => {
                    function waitMap (){
                        that.initMap();
                    }
                    waitMap();
                }
				amapBox.insertAdjacentElement("beforeend", script2);
            }; 
            amapBox.insertAdjacentElement("beforeend", script1);
			document.body.appendChild(amapBox);
        },
        //初始化地图
        initMap(){
            var that = this;
            var addParams = this.$route.query;
            var adderssArr = [];
            try{
                var map = new AMap.Map('allmap', {
                    resizeEnable: true,
                    zoom: 15,
                    center: [108.383765, 22.813923],
                    scrollWheel : true
                });
            }catch(err) {
                console.log('erere')
                setTimeout(() => {
                    that.initMap();
                },150)
                return false
            }
            var shop;
			var kmReg = /\d+km/;
			//所有marker的集合，用于地图自适应缩放
			var markerList = [];
			var tenSecond = false;
			var tenTimer;
            function pursue() {
                map.plugin(['AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Autocomplete', "AMap.Geocoder"], function() {
                    var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true, //是否使用高精度定位，默认:true
                        timeout: 5000, //超过10秒后停止定位，默认：无穷大
                        maximumAge: 0, //定位结果缓存0毫秒，默认：0
                        convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                        showButton: true, //显示定位按钮，默认：true
                        buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
                        buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
                        showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
                        panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                        zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false,
                    });
                    var placeSearch = new AMap.PlaceSearch({
                        pageSize: 10,
                        pageIndex: 1,
                        map: map,
                        autoFitView : true
                    });
                    that.locateSpot = [{"address":"定位中..."}];
                    map.addControl(geolocation);
                    geolocation.getCurrentPosition();
                    //添加定位失败和定位成功的监听事件
                    geolocation.on("complete", function (result) {
                        let lists = [];
                        let obj = {};
                        let Pos = {};
                        var RnParams = {
                            type: RECEIVE_DISTANCE,
                            params: {
                                currentPos: result
                            }
                        }
                        window.postMessage(JSON.stringify(RnParams));
                        if(result.addressComponent) {
                            result.formateAdd = result.addressComponent.city + result.addressComponent.district + result.addressComponent.street + result.addressComponent.streetNumber;
                        }else {
                            that.locateStatus = '定位失败';
                            that.locateSpot = [{"address":"定位失败"}]
                            console.log('这个经纬度高德没有具体的地理信息,用经纬度api再去查询也没有,当作定位失败处理')
                            return false;
                        }
                        lists.push(result);
                        that.locateSpot = lists;
                        lists.forEach((item,index) => {
                            that.polygonList.forEach((element,indent) => {
                                let lnglat = new AMap.LngLat(item.position.lng, item.position.lat);
                                if(element.contains(lnglat)) {
                                    item.inArea = true;
                                    if(that.areaList.length) {
                                        item.storeCode = that.matchStoreCode(that.areaList[indent].deptid)
                                    }
                                }
                            })
                        })
                        if(result.inArea && result.addressComponent){
                            obj.province = result.addressComponent.province;
                            obj.city = result.addressComponent.city || '市辖区';
                            obj.region = result.addressComponent.district;
                            obj.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;
                            obj.positionlng = result.position.lng;
                            obj.positionlat = result.position.lat;
                            obj.addressid = "-1";
                            Pos.province = result.addressComponent.province;
                            Pos.city = result.addressComponent.city || '市辖区';
                            Pos.region = result.addressComponent.district;
                            Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                            Pos.positionlng = result.position.lng;
                            Pos.positionlat = result.position.lat;
                            Pos.addressid = "-1";
                            Pos.inArea = true;
                            // 没有选择地址
                            if(that.storeCode) {
                                if(that.addressid === 'noAddress') {
                                    that.sendAddToRn(obj);
                                    that.updateChoosedAddress(obj)
                                }else {
                                    let lastLocation;
                                    that.getAddressList.length && that.getAddressList.map(ele => {
                                        if(ele.addressid == that.addressid) {
                                            lastLocation = ele
                                        }
                                    })
                                    if(lastLocation) {
                                        let config = {
                                            url: api.tmsUrl + 'centralManagerApi/centralManagerObject',
                                            method: 'post',
                                            data: {
                                                judgeInBaselatticeByStoreId: {
                                                    longitudeandlatitude: lastLocation.positionlng + ',' + lastLocation.positionlat,
                                                    storeIdList: that.getVaildStoreIdList()
                                                }
                                            }
                                        }
                                        axios(config).then(res => {
                                            if(res.data.returnCode) {
                                                
                                            }else {
                                                // 选择的地址不再配送范围内
                                                that.sendAddToRn(obj);
                                                that.updateChoosedAddress(obj)
                                            }
                                        })
                                    }else {
                                        // 原本选择的配送地址不存在了
                                        that.sendAddToRn(obj);
                                        that.updateChoosedAddress(obj)
                                    }
                                }
                            }
                            localStorage.setItem("locateIn", JSON.stringify(obj));
                            localStorage.setItem("currentPos", JSON.stringify(Pos));
                            if(that.addressid == 'noAddress') {
                                (!that.locationInfo || !Object.keys(that.locationInfo).length) && that.$store.dispatch('qxz/updateLocation', obj);
                            }
                        }else if(!result.inArea && result.addressComponent){
                            obj.tip = '当前位置不可配送，请输入您的收货地址';
                            obj.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                            obj.province = result.addressComponent.province;
                            obj.city = result.addressComponent.city;
                            obj.formateAdd = result.formattedAddress;
                            obj.positionlng = result.position.lng;
                            obj.positionlat = result.position.lat;
                            Pos.inArea = false;
                            Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;
                            Pos.province = result.addressComponent.province;
                            Pos.city = result.addressComponent.city;
                            Pos.formateAdd = result.formattedAddress;
                            Pos.positionlng = result.position.lng;
                            Pos.positionlat = result.position.lat;
                            Pos.inArea = false;
                            localStorage.setItem("locateOut", JSON.stringify(obj));
                            localStorage.setItem("currentPos", JSON.stringify(Pos));
                            console.log(that.addressid,that.formerAddressInvaild,'that.formerAddressInvaild')
                            if(that.addressid == 'noAddress' || that.formerAddressInvaild) {
                                that.$store.dispatch('qxz/updateScopeOut', obj);
                                that.$store.dispatch('qxz/updateLocation', {});
                            }
                        }
                        localStorage.setItem('poslng', result.position.lng);
                        localStorage.setItem('poslat', result.position.lat);
                        let cpoint = [];
                        cpoint.push(result.position.lng);
                        cpoint.push(result.position.lat);
                        var maxNearPoi = 3;
                        placeSearch.searchNearBy("",cpoint,200,function(status,res){
                            let nearPoint = res.poiList ? res.poiList.pois : [];
                            nearPoint.length > 3 ? nearPoint.length = 3 : "";
                            nearPoint && nearPoint.forEach((item,index) => {
                                that.polygonList.forEach((element,indent) => {
                                    let lnglat = new AMap.LngLat(item.location.lng, item.location.lat);
                                    if(element.contains(lnglat)) {
                                        item.inArea = true;
                                        if(that.areaList.length) {
                                            item.storeCode = that.matchStoreCode(that.areaList[indent].deptid)
                                        }
                                    }
                                })
                            })
                            nearPoint.length && (that.vicintyList = nearPoint);
                        })
                    });
                    geolocation.on("error", function (err) {
                        that.locateStatus = '定位失败';
                        that.locateSpot = [{"address":"定位失败"}]
                        console.log(err,'error')
                    });
                })
            }
            (function () {
				var isShow = false;
				//请求配送范围的经纬度数组
                let url = api.tmsUrl + 'centralManagerApi/centralManagerObject';
                if(document.querySelector("#search-input")){
                    document.querySelector("#search-input").onkeyup = function(){
                        this.value == "" ? that.positionList = [] : "";
                    }
                }
				axios.post(url,{
                    getAllBaselatticeByStoreId: {
                        storeIdList: that.getVaildStoreIdList()
                    }
                }).then(function (res) {
                    that.polygonList = [];
                    //门店配送范围
                    let array = new Array();
                    for(let item of res.data.data[0]){
                        let Arr = new Array();
                        for(let it of JSON.parse(item.longitudeandlatitude)){
                            let arr = new Array();
                            arr[0] = it.a;
                            arr[1] = it.b;
                            Arr.push(arr);
                        }
                        // if(that.storeCode) {
                        //     that.matchStoreCode(item.deptid) == that.storeCode && array.push(Arr);
                        //     // array.push(Arr);
                        // }else {
                            array.push(Arr)
                            that.areaList.push(item);
                        // }
                    }
                    
                    //多边形覆盖物节点坐标数组
                    for (let item of array){
                        var polygon = new AMap.Polygon({
                            map: map,
                            path: item,//设置多边形边界路径
                            strokeColor: "red", //线颜色
                            strokeOpacity: 0.2, //线透明度
                            strokeWeight: 3,    //线宽
                            fillColor: "red", //填充色
                            fillOpacity: 0.35//填充透明度
                        });
                        polygon.setMap(map);
                        that.polygonList.push(polygon);
                    }
                    pursue();
                })
                .catch(function (res) {
                    //console.log(res);
                });
			})();
        },
        //判断ios版本
        getIosVersion() {
            var u = navigator.userAgent, app = navigator.appVersion;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
            var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            if (isAndroid) {
                //这个是安卓操作系统
                return false
            }
            if (isIOS) {
        　　　　 //这个是ios操作系统
                var ver = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
                // ver = parseInt(ver[1], 10);
                var IosVersion = (ver[1] || '0') + (ver[2] || '0') + (ver[3] || '0');
                if(Number(IosVersion) < 935) {
                    return true
                }else {
                    return false
                }
            }
        },
        //重新定位
        relocate(){
            this.locateSpot = [{"address":"定位中..."}]
            var that = this;
            var addParams = this.$route.query;
			var adderssArr = [];
            var map = new AMap.Map('allmap', {
				resizeEnable: true,
				zoom: 15,
				center: [108.383765, 22.813923],
				scrollWheel : true
            });
            var shop;
			var kmReg = /\d+km/;
			//所有marker的集合，用于地图自适应缩放
			var markerList = [];
			var tenSecond = false;
            var tenTimer;
            map.plugin(['AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Autocomplete', "AMap.Geocoder"], function() {
				//给一个定位过程的loading
				var geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 5000, //超过10秒后停止定位，默认：无穷大
					maximumAge: 0, //定位结果缓存0毫秒，默认：0
					convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
					showButton: true, //显示定位按钮，默认：true
					buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
					buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
					showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
					panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
					zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false,
				});

				map.addControl(geolocation);
				geolocation.getCurrentPosition();
				
				//添加定位失败和定位成功的监听事件
				geolocation.on("complete", function (result) {
                    //关闭loading效果
                    let lists = [];
                    let obj = {};
                    let Pos = {};
                    var RnParams = {
                        type: RECEIVE_DISTANCE,
                        params: {
                            currentPos: result
                        }
                    }
                    window.postMessage(JSON.stringify(RnParams));
                    if(result.addressComponent) {
                        result.formateAdd = result.addressComponent.city + result.addressComponent.district + result.addressComponent.street + result.addressComponent.streetNumber;
                    }else {
                        that.locateStatus = '定位失败';
                        that.locateSpot = [{"address":"定位失败"}]
                        console.log('这个经纬度高德没有具体的地理信息,用经纬度api再去查询也没有,当作定位失败处理')
                        return false;
                    }
                    lists = [result];
                    that.locateSpot = [result];
                    lists.forEach((item,index) => {
                        that.polygonList.forEach((element,indent) => {
                            let lnglat = new AMap.LngLat(item.position.lng, item.position.lat);
                            if(element.contains(lnglat)) {
                                item.inArea = true;
                                if(that.areaList.length) {
                                    item.storeCode = that.matchStoreCode(that.areaList[indent].deptid)
                                }
                            }
                        })
                    })
                    that.searchCity = result.addressComponent.city || result.addressComponent.province;
                    // console.log(that.searchCity,"searchCity");
                    if(result.inArea && result.addressComponent){
                        obj.province = result.addressComponent.province;
                        obj.city = result.addressComponent.city || '市辖区';
                        obj.region = result.addressComponent.district;
                        obj.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;
                        obj.positionlng = result.position.lng;
                        obj.positionlat = result.position.lat;
                        obj.addressid = "-1";
                        Pos.province = result.addressComponent.province;
                        Pos.city = result.addressComponent.city || '市辖区';
                        Pos.region = result.addressComponent.district;
                        Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                        Pos.positionlng = result.position.lng;
                        Pos.positionlat = result.position.lat;
                        Pos.addressid = "-1";
                        Pos.inArea = true;
                        // 没有选择地址
                        if(that.storeCode) {
                            if(that.addressid === 'noAddress') {
                                that.sendAddToRn(obj);
                                that.updateChoosedAddress(obj)
                            }else {
                                let lastLocation;
                                that.getAddressList.length && that.getAddressList.map(ele => {
                                    if(ele.addressid == that.addressid) {
                                        lastLocation = ele
                                    }
                                })
                                if(lastLocation) {
                                    let config = {
                                        url: api.tmsUrl + 'centralManagerApi/centralManagerObject',
                                        method: 'post',
                                        data: {
                                            judgeInBaselatticeByStoreId: {
                                                longitudeandlatitude: lastLocation.positionlng + ',' + lastLocation.positionlat,
                                                storeIdList: that.getVaildStoreIdList()
                                            }
                                        }
                                    }
                                    axios(config).then(res => {
                                        if(res.data.returnCode) {
                                            
                                        }else {
                                            // 选择的地址不再配送范围内
                                            that.sendAddToRn(obj);
                                            that.updateChoosedAddress(obj)
                                        }
                                    })
                                }else {
                                    // 原本选择的配送地址不存在了
                                    that.sendAddToRn(obj);
                                    that.updateChoosedAddress(obj)
                                }
                            }
                        }
                        localStorage.setItem("locateIn", JSON.stringify(obj));
                        localStorage.setItem("currentPos", JSON.stringify(Pos));
                        // if(that.addressid == 'noAddress') {
                            that.$store.dispatch('qxz/updateLocation', obj);
                        // }
                    }else if(!result.inArea && result.addressComponent){
                        obj.tip = '当前位置不可配送，请输入您的收货地址';
                        obj.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                        obj.province = result.addressComponent.province;
                        obj.city = result.addressComponent.city;
                        obj.formateAdd = result.formattedAddress;
                        obj.positionlng = result.position.lng;
                        obj.positionlat = result.position.lat;
                        Pos.inArea = false;
                        Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;
                        Pos.province = result.addressComponent.province;
                        Pos.city = result.addressComponent.city;
                        Pos.formateAdd = result.formattedAddress;
                        Pos.positionlng = result.position.lng;
                        Pos.positionlat = result.position.lat;
                        Pos.inArea = false;
                        localStorage.setItem("locateOut", JSON.stringify(obj));
                        localStorage.setItem("currentPos", JSON.stringify(Pos));
                        if(that.addressid == 'noAddress' || that.formerAddressInvaild) {
                            that.$store.dispatch('qxz/updateScopeOut', obj);
                            that.$store.dispatch('qxz/updateLocation', {});
                        }
                    }
                    localStorage.setItem('poslng', result.position.lng);
                    localStorage.setItem('poslat', result.position.lat);
                    
                    var auto = new AMap.Autocomplete ({
                        city: that.searchCity,
                        // input: 'search-input'
                    });

                    let cpoint = [];
                    cpoint.push(result.position.lng);
                    cpoint.push(result.position.lat);
                    var maxNearPoi = 3;
                    placeSearch.searchNearBy("",cpoint,200,function(status,res){
                        let nearPoint = res.poiList ? res.poiList.pois : [];
                        nearPoint.length > 3 ? nearPoint.length = 3 : "";
                        nearPoint && nearPoint.forEach((item,index) => {
                            that.polygonList.forEach((element,indent) => {
                                let lnglat = new AMap.LngLat(item.location.lng, item.location.lat);
                                if(element.contains(lnglat)) {
                                    item.inArea = true;
                                    if(that.areaList.length) {
                                        item.storeCode = that.matchStoreCode(that.areaList[indent].deptid)
                                    }
                                }
                            })
                        })
                        nearPoint.length && (that.vicintyList = nearPoint);
                    })
				});
				geolocation.on("error", function (err) {
                    console.log(err, 'here')
                    that.locateSpot = [{"address":"定位失败"}];
                    that.locateStatus = '定位失败';
                });

				var placeSearch = new AMap.PlaceSearch({
					pageSize: 10,
					pageIndex: 1,
					map: map,
					autoFitView : true
				});
				placeSearch.on("complete", function (e) {
                    console.log(e,"搜索成功");
                });
            });
            (function () {
				var isShow = false;
                //请求配送范围的经纬度数组
                let url = api.tmsUrl + 'centralManagerApi/centralManagerObject';
                if(document.querySelector("#search-input")){
                    document.querySelector("#search-input").onkeyup = function(){
                        this.value == "" ? that.positionList = [] : "";
                    }
                }
				axios.post(url,{
						getAllBaselatticeByStoreId: {
                            storeIdList: that.getVaildStoreIdList()
                        }
					})
					.then(function (res) {
						that.polygonList = [];
						//门店配送范围
						let array = new Array();
						for(let item of res.data.data[0]){
							let Arr = new Array();
							for(let it of JSON.parse(item.longitudeandlatitude)){
								let arr = new Array();
								arr[0] = it.a;
								arr[1] = it.b;
								Arr.push(arr);
                            }
                            // if(that.storeCode) {
                            //     that.matchStoreCode(item.deptid) == that.storeCode && array.push(Arr);
                            // }else {
                                array.push(Arr)
                                that.areaList.push(item)
                            // }
						}
						//多边形覆盖物节点坐标数组
						for (let item of array){
							var polygon = new AMap.Polygon({
								map: map,
								path: item,//设置多边形边界路径
								strokeColor: "red", //线颜色
								strokeOpacity: 0.2, //线透明度
								strokeWeight: 3,    //线宽
								fillColor: "red", //填充色
								fillOpacity: 0.35//填充透明度
							});
							polygon.setMap(map);
							that.polygonList.push(polygon);
						}
						// console.log(that.polygonList,"polygonList")
					})
					.catch(function (res) {
						//console.log(res);
					});
			})();
        },
        //前往地图页面
        ToMap(){
            this.$router.push({path:"map",query:{fromShopList: this.fromShopList, storeCode: this.storeCode}});
        },
        //搜索地址
        searchEvent(){
            // console.log(this.searchCity,'当前城市');
            let searchCity = this.searchCity;
            var auto = new AMap.Autocomplete ({
                // city: searchCity,
                // city: "上海",
                // input: 'search-input'
            });
            let autocomplete = new AMap.Autocomplete(auto);
            autocomplete.search(this.keyword, (status, e) => {
                //TODO:开发者使用result自己进行下拉列表的显示与交互功能
                let assumeListUL = this.$refs.assumeListUL;
                let assumeList = this.$refs.assumeList;
                assumeList.style.maxHeight = this.clientHeight - 120 + "px";
                let Arr = new Array();
                let priorityList = new Array();
                let restList = new Array();
                e.tips && e.tips.map((item,index) => {
                    item.location && item.location.lng && Arr.push(item);
                },this)
                Arr.length && Arr.map((item,index) => {
                    this.polygonList.map((element,indent) => {
                        let lnglat = new AMap.LngLat(item.location.lng, item.location.lat);
                        if(element.contains(lnglat)) {
                            item.inArea = true;
                            if(this.areaList.length) {
                                console.log(this.matchStoreCode(this.areaList[indent].deptid),'item')
                                item.storeCode = this.matchStoreCode(this.areaList[indent].deptid)
                            }
                        }
                    })
                })
                Arr.forEach(item => {
                    item.inArea ? priorityList.push(item) : restList.push(item);
                })
                let TerminalList = priorityList.concat(restList);
                this.positionList = TerminalList || [];
            });
        }
    },
    watch:{
        locationInfo(newVal){
            if(newVal){
                this.judgeInArea()
                // console.log(newVal,"locationInfo")
                let storeCode = newVal.storeCode;
                this.storeList.forEach((item,index) => {
                    if(storeCode == item.storeCode){
                        localStorage.setItem("storeCode", storeCode);
                        localStorage.setItem("storeId", item.storeId);
                        localStorage.setItem("storeName", item.storeName);
                        localStorage.setItem("storeLng", item.positionLng);
                        localStorage.setItem("storeLat", item.positionLat);
                        window.api.storeCode = storeCode;
                        localStorage.setItem("locateIn", JSON.stringify(newVal));
                        // this.$store.dispatch('cjy/storeCodeOnChange');
                    }
                },this)
            }
        },
        choosedBefore(newVal) {
            if(newVal){
                this.judgeInArea()
            }
        },
        ScopeOutInfo(newVal) {
            if(newVal){
                this.judgeInArea()
            }
        },
        keyword(newVal){
            let perChoose = document.querySelector('#perChoose');
            newVal.length ? perChoose.style.overflow = 'hidden' : perChoose.style.overflow = 'auto'
            this.searchEvent();
        }
    }
}
</script>
<style scoped>
.container{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    position: relative;
}
.shade{
    position:absolute;
    left:0;
    top:2.2rem;
    bottom: 0;
    width: 100%;
    background: #000;
    opacity: .3;
    z-index: 1;
}
.bottomBtn{
    width: 100%;
    height: 3rem;
    background: #EF5423;
    text-align: center;
    line-height: 3rem;
    color: white;
    font-size: 1rem;
}
#perChoose{
    width: 100%;
    flex: 1;
    overflow: auto;
}
ul,ol,li{
    margin:0;
    padding:0;
    list-style: none;
}
p{
    margin: 0;
    padding: 0;
}
.searcher{
    width: 100%;
    height: 2.4rem;
    background: white;
    /* border-top:1px solid #eaeaea; */
}
.location{
    width: 100%;
    height: 1.7rem;
    background: #FFFBD9;
    color: #7FB65F;
    text-align: left;
    box-sizing: border-box;
    padding-left: .5rem;
    display: flex;
    align-items: center;
    justify-content: "flex-start";
}
.redLocation{
    width: 100%;
    height: 1.7rem;
    background: #FFF3EE;
    color: rgba(243, 65, 11, 0.932);
    text-align: left;
    box-sizing: border-box;
    padding-left: .5rem;
    display: flex;
    align-items: center;
    justify-content: "flex-start";
}
.greenLocation{
    width: 100%;
    height: 1.7rem;
    background: #E2EEE2;
    color: #7FB65F;
    text-align: left;
    box-sizing: border-box;
    padding-left: .5rem;
    display: flex;
    align-items: center;
    justify-content: "flex-start";
}
.deliveryAdd{
    width: 100%;
    height: 1.8rem;
    line-height: 1.8rem;
    text-align: left;
    text-indent: .8rem;
    font-size: .8rem;
    color: #A3A3A3;
    border-top: 1px solid #EDEDED;
    border-bottom: 1px solid #EDEDED;
}
.amap-sug-result{
    display: none !important;
}

.vicinty{
    background: white;
    font-size: .9rem;
}
.assumeList{
    position: absolute;
    z-index: 2;
    left: 0;
    top: 2.2rem;
    width: 100%;
    overflow: hidden;
}
.assumeList ul{
    width: 100%;
}
.assumeList ul li{
    width: 100%;
    box-sizing: border-box;
    padding: 0 .7rem;
    height: 2.7rem;
    border-bottom: 1px solid #ccc;
    text-align: left;
    background: white;
}
.assumeList ul li p{
    width: 95%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.locateSpot{
    width: 100%;
    height: 2rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: .2rem .7rem;
}
.nearlySpot{
    height: 2rem;
    text-align: left;
}
.nearlySpot p{
    margin: 0;
    width: 100%;
    height: 100%;
    color: black;
    line-height: 2rem;
    border-bottom: 1px solid #ccc;
    text-indent: .7rem;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.firstItem{
    border-top: 1px solid #ccc;
}
.moreLocation{
    width: 100%;
    height: 2rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 .7rem;
    font-size: .75rem;
}
.deliveryAddress{
    font-size: .75rem;
    width: 90%;
    text-indent: .4rem;
    color:#7C7C7B;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.deliveryAddressPos{
    font-size: .75rem;
    width: 90%;
    text-indent: .4rem;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
#search-input{
    width: 85%;
    height:100%;
    font-size: .85rem;
    outline: none;
}
.searcherContainer{
    background:#F5F5F5;
    width:94%;
    height:2.2em;
    margin-left:3%;
    border:1px solid #eaeaea;
    border-radius: .2rem;
    background:white;
    display:flex;
    align-items:center;
    justify-content:flex-start;
}
.firstLocation{
    display: inline-block;
    width: 70%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    text-align: left;
    -webkit-tap-highlight-color:transparent;
    font-size:.75rem;
}
#arrow{
    font-size:.85rem;
}
</style>